import numpy as np
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
import pandas as pd
import scipy.cluster.hierarchy as sch
from scipy.cluster.hierarchy import dendrogram, linkage, set_link_color_palette
import seaborn as sns
from sklearn import preprocessing

df = pd.read_csv("F:/成信大/多元统计分析/test3-2.csv")
data = df.columns[1: 9]
# 获取第一列数据，方便后面分组
place = np.mat(df[df.columns[0:1]])
u = df[data]
# Z-Score数据标准化处理
x_scaled = preprocessing.scale(u)

'''
热力图
sns.set()
cor = df.corr()
sns.heatmap(cor, square=True)
plt.show()
'''

'''
聚类结果图
ZT = linkage(np.transpose(x_scaled), 'ward')
dendrogram(ZT, labels=u.columns, orientation='right')
my_palette = plt.cm.get_cmap("Accent", 4)
plt.show()
'''
# K-mean聚类分析
cls = KMeans(3).fit(x_scaled)
# 获取具体数据
cls = cls.labels_
# 分组
groups = [[], [], []]
j = 0
# 通过KMeans获得的数据结合place，将数据分为3组
for i in cls:
    if i == 1:
        groups[i].append(place[j])
    elif i == 2:
        groups[i].append(place[j])
    else:
        groups[i].append(place[j])
    j = j + 1
for element in enumerate(groups):
    print(len(element[1]), element)

